<?php declare(strict_types=1);

namespace App\Services\Store;


use App\Models\Store;
use App\Models\UserRate;

class StoreService
{

    public function getUserRateList(string $company, array $prevUserList): array
    {
        //在这里获取上级
        $userIds = array_column($prevUserList, "id");
        //查询上级费率
        $userRateList = UserRate::query()->select([
            "user_rates.user_id", "user_rates.rate", "user_rates.rate_a", "user_rates.rate_c", "user_rates.rate_e", "user_rates.rate_f",
            "user_rates.rate_f_top", "user_rates.ways_type", "user_rates.company",
            'user_rates.server_rate',
            'user_rates.yu_rate',
            'user_rates.era_rate',
            "store_ways_desc.ways_source"
        ])
            ->leftJoin("store_ways_desc", "store_ways_desc.ways_type", "=", "user_rates.ways_type")
            ->where("user_rates.company", $company)->whereIn("user_rates.user_id", $userIds)->get()->toArray();
        //归档整理数据
        $userRateTmp = [];
        foreach ($userRateList as $userRate) {
            $userRateTmp[$userRate["user_id"]][$userRate["ways_source"]] = $userRate;
        }
        //将数据整理到层级关系中
        foreach ($prevUserList as $k => $user) {
            //整理数据
            $tmp = [
                "rate_a" => $userRateTmp[$user["id"]]["unionpay"]["rate_a"] ?? 0,
                "rate_c" => $userRateTmp[$user["id"]]["unionpay"]["rate_c"] ?? 0,
                "rate_e" => $userRateTmp[$user["id"]]["unionpay"]["rate_e"] ?? 0,
                "rate_f" => $userRateTmp[$user["id"]]["unionpay"]["rate_f"] ?? 0,
                "rate_f_top" => $userRateTmp[$user["id"]]["unionpay"]["rate_f_top"] ?? 0,
                "rate_bestpay" => $userRateTmp[$user["id"]]["Bestpay"]["rate"] ?? 0, //翼支付
                "rate_wx" => $userRateTmp[$user["id"]]["weixin"]["rate"] ?? 0, //翼支付
                "rate_alipay" => $userRateTmp[$user["id"]]["alipay"]["rate"] ?? 0, //翼支付

                "server_rate" => current($userRateTmp[$user["id"]])["server_rate"] ?? 0,
                "yu_rate" => current($userRateTmp[$user["id"]])["yu_rate"] ?? 0,
                "era_rate" => current($userRateTmp[$user["id"]])["era_rate"] ?? 0,
            ];

            $user["rate"] = $tmp;

            $prevUserList[$k] = $user;
        }
        //数组反转
        $prevUserList = array_reverse($prevUserList);
        return $prevUserList;
    }

}